package gov.kqqzyyy.monkey.clinicscreen.ui;

import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.SwitchPreference;
import android.view.KeyEvent;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.socks.library.KLog;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import gov.kqqzyyy.monkey.clinicscreen.R;
import gov.kqqzyyy.monkey.clinicscreen.mytools.ProgressDialogFragment;
import gov.kqqzyyy.monkey.clinicscreen.mytools.UpdateInfo;
import gov.kqqzyyy.monkey.clinicscreen.network.RetrofitUtil;
import gov.kqqzyyy.monkey.clinicscreen.network.base.BaseObserver;
import gov.kqqzyyy.monkey.clinicscreen.network.bean.BaseResponse;
import gov.kqqzyyy.monkey.clinicscreen.objects.ClinicArea_New;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

@SuppressWarnings("NullableProblems")
public class FragmentPreferences extends Activity {

    //    private List<ZQ_ZQXX> mResultList;
    private List<ClinicArea_New> clinicAreaList;

    private ProgressDialogFragment progressDialogFragment;

//    private Call<String> zqxxCall;

    private PrefsFragement prefsFragement;

    private BaseObserver<List<ClinicArea_New>> clinicObserver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        doGetZQXX();
        doGetClinicArea();
    }

    @Override
    protected void onStop() {
        super.onStop();
//        if (zqxxCall != null && zqxxCall.isExecuted()) {
//            zqxxCall.cancel();
//        }
        if (clinicObserver != null) {
            clinicObserver.doCancelRequest();
        }
        if (prefsFragement != null && prefsFragement.serverTestThread != null && prefsFragement.serverTestThread.isAlive()) {
            prefsFragement.serverTestThread.interrupt();
            prefsFragement.serverTestThread = null;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(getApplicationContext(), SplashActivity.class);
            startActivity(intent);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

//    public List<ZQ_ZQXX> getmResultList() {
//        return mResultList;
//    }

    public List<ClinicArea_New> getClinicAreaList() {
        return clinicAreaList;
    }

    // 设置类
    public static class PrefsFragement extends PreferenceFragment implements Preference.OnPreferenceChangeListener {

        SharedPreferences mSharedPreferences;
        ListPreference mClinicAreaPreference; //诊区列表
        ListPreference mClinicCallAreaPreference;//诊区分区列表
        EditTextPreference mServerAddPreference; //服务器地址
        SwitchPreference switchPreference;
        SwitchPreference proficientSwitch;//专家显示
        SwitchPreference soundSwitch;
        SwitchPreference docNameSwitch;

        String defaultClinic;
        String defaultClinicArea;
        String preServerAdd;

        MyHandler myHandler;
        Thread serverTestThread;

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mSharedPreferences = getPreferenceManager().getSharedPreferences();
            myHandler = new MyHandler((FragmentPreferences) getActivity());
            addPreferencesFromResource(R.xml.preferences);//从XML文件加载选项
            onBindXML();
            setAddressText();
            mServerAddPreference.setOnPreferenceChangeListener(this);
//            mResultList = ((FragmentPreferences) getActivity()).getmResultList();
            //        List<ZQ_ZQXX> mResultList;
            List<ClinicArea_New> clinicAreaList = ((FragmentPreferences) getActivity()).getClinicAreaList();
//            if (mResultList.size() > 0) {
            if (clinicAreaList.size() > 0) {
                //诊区名称
                List<String> zqmcList = new ArrayList<>();
                //诊区识别
                List<String> zqidList = new ArrayList<>();

                String[] zqfqidArray = getResources().getStringArray(R.array.clinic_callarea_entryvalues);
                List<String> zqfqidList = Arrays.asList(zqfqidArray);
                String[] zqfqmcArray = getResources().getStringArray(R.array.clinic_callarea_entries);

//                for (ZQ_ZQXX zqxx : mResultList
//                ) {
//                    zqmcList.add(zqxx.getZQMC());
//                    zqidList.add(zqxx.getZQID());
//                }
                for (ClinicArea_New clinicArea : clinicAreaList
                ) {
                    zqmcList.add(clinicArea.getName());
                    zqidList.add(clinicArea.getCode());
                }

                CharSequence[] zqmcArray = zqmcList.toArray(new CharSequence[0]);
                CharSequence[] zqsbArray = zqidList.toArray(new CharSequence[0]);
                mClinicAreaPreference.setEntries(zqmcArray);
                mClinicAreaPreference.setEntryValues(zqsbArray);
                mClinicAreaPreference.setOnPreferenceChangeListener(this);
                mClinicCallAreaPreference.setOnPreferenceChangeListener(this);
                defaultClinic = mSharedPreferences.getString("clinicarea_name", "");
                defaultClinicArea = mSharedPreferences.getString("clinic_area_preference", "");

                if (!"".equals(defaultClinic)) {
                    mClinicAreaPreference.setSummary(defaultClinic);
                    int index = Math.max(zqmcList.indexOf(defaultClinic), 0);
                    mClinicAreaPreference.setValueIndex(index);
                } else {
                    mClinicAreaPreference.setValueIndex(0);
                    mClinicAreaPreference.setSummary(zqmcArray[0]);
                    mSharedPreferences.edit().putString("clinicarea_name", zqmcArray[0].toString()).apply();
                }

                if (!"".equals(defaultClinicArea)) {
                    int index = zqfqidList.indexOf(defaultClinicArea);
                    mClinicCallAreaPreference.setSummary(zqfqmcArray[index]);
                    mClinicCallAreaPreference.setValueIndex(index);
                } else {
                    mClinicCallAreaPreference.setValueIndex(0);
                }

                switchPreference.setOnPreferenceChangeListener(this);
                if (switchPreference.isChecked()) {
                    switchPreference.setTitle("开启");
                }

                proficientSwitch.setOnPreferenceChangeListener(this);
                if (proficientSwitch.isChecked()) {
                    proficientSwitch.setTitle("开启");
                }

            }
        }

        private void setAddressText() {
            preServerAdd = mSharedPreferences.getString("server_address", getString(R.string.default_server));
            mServerAddPreference.setText(preServerAdd);
            mServerAddPreference.setSummary(preServerAdd);
        }

        private void onBindXML() {
            mServerAddPreference = (EditTextPreference) findPreference("server_address");
            mClinicAreaPreference = (ListPreference) findPreference("clinic_preference");
            mClinicCallAreaPreference = (ListPreference) findPreference("clinic_area_preference");
            switchPreference = (SwitchPreference) findPreference("normal_clinic_open");
            proficientSwitch = (SwitchPreference) findPreference("proficient_show");
            soundSwitch = (SwitchPreference) findPreference("sound_preference");
            docNameSwitch = (SwitchPreference) findPreference("adddocname_preference");
        }

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (preference.getKey().equals("normal_clinic_open") || preference.getKey().equals("proficient_show")) {
                boolean result = (boolean) newValue;
                String text = result ? "开启" : "关闭";
                preference.setTitle(text);
            } else if (preference instanceof ListPreference) {
                ListPreference listPreference = (ListPreference) preference;
                CharSequence[] entries = listPreference.getEntries();
                int index = listPreference.findIndexOfValue((String) newValue);
                listPreference.setSummary(entries[index]);
                boolean isChanged = !newValue.toString().equals(defaultClinic) || !newValue.toString().equals(defaultClinicArea);
                if (isChanged) {
                    if (preference.getKey().equals("clinic_preference")) {
                        defaultClinic = newValue.toString();
                        mSharedPreferences.edit().putString("clinicarea_name", (String) entries[index]).apply();
                    }
                }
            } else {
                ((FragmentPreferences) getActivity()).showProgressDialog("服务器连接测试中");
                final String newAdd = newValue.toString();
                serverTestThread = new Thread(() -> {
                    Message message = new Message();
                    if (UpdateInfo.isServerAvailable(newAdd)) {
                        message.what = 0x11;
                    } else {
                        message.what = 0x12;
                        mSharedPreferences.edit().putString("server_address", preServerAdd).apply();
                    }
                    myHandler.sendMessage(message);
                    serverTestThread.interrupt();
                    serverTestThread = null;
                });
                serverTestThread.start();
            }
            return true;
        }

    }

    private static class MyHandler extends Handler {
        WeakReference<FragmentPreferences> mActivity;

        MyHandler(FragmentPreferences activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            FragmentPreferences activity = mActivity.get();
            activity.cancelProgressDialog();
            switch (msg.what) {
                case 0x11:
                    Toast.makeText(activity, "服务器连接成功,重启该界面", Toast.LENGTH_SHORT).show();
                    activity.doRestart();
                    break;
                case 0x12:
                    Toast.makeText(activity, "服务器连接失败，重置默认地址", Toast.LENGTH_SHORT).show();
                    break;
            }
            activity.prefsFragement.setAddressText();
        }
    }

    private void doRestart() {
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

//    private void doGetZQXX() {
//        showProgressDialog("获取诊区信息中");
//        zqxxCall = MyServiceUtil.getClinicAreaCall();
//        Callback<String> callback = new Callback<String>() {
//            @Override
//            public void onResponse(Call<String> call, Response<String> response) {
//                cancelProgressDialog();
//                Gson gson = new Gson();
//                String result = response.body();
//                if (result != null) {
//                    mResultList = gson.fromJson(result, new TypeToken<List<ZQ_ZQXX>>() {
//                    }.getType());
//                    if (mResultList != null && mResultList.size() > 0) {
//                        prefsFragement = new PrefsFragement();
//                        getFragmentManager().beginTransaction().replace(android.R.id.content, prefsFragement).commit();
//                    }
//                } else {
//                    showEmptyChoose();
//                }
//            }
//
//            @Override
//            public void onFailure(Call<String> call, Throwable t) {
//                cancelProgressDialog();
//                Toast.makeText(getApplicationContext(), "获取诊区失败" + t.toString(), Toast.LENGTH_SHORT).show();
//                showEmptyChoose();
//            }
//        };
//        zqxxCall.enqueue(callback);
//    }

    private void doGetClinicArea() {
        Observable<BaseResponse<List<ClinicArea_New>>> observable = RetrofitUtil.getInstence().getClinicAreas();
        clinicObserver = new BaseObserver<List<ClinicArea_New>>() {
            @Override
            protected void onSuccees(BaseResponse<List<ClinicArea_New>> result) {
                clinicAreaList = result.getData();
                if (clinicAreaList != null) {
                    prefsFragement = new PrefsFragement();
                    getFragmentManager().beginTransaction().replace(android.R.id.content, prefsFragement).commit();
                } else {
                    showEmptyChoose();
                }
            }

            @Override
            protected void onFailure(Throwable e, boolean isNetWorkError) {
                KLog.d("APE", e);
            }

            @Override
            protected void onCodeError(BaseResponse<List<ClinicArea_New>> t) {
                super.onCodeError(t);
                KLog.d("APE", t);
            }
        };
        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(clinicObserver);
    }


    private void showEmptyChoose() {
        Toast.makeText(getApplicationContext(), "获取诊区失败", Toast.LENGTH_SHORT).show();
//        mResultList = new ArrayList<>();
        clinicAreaList = new ArrayList<>();
        PrefsFragement prefsFragement = new PrefsFragement();
        FragmentManager fragmentManager = getFragmentManager();
        if (fragmentManager != null) {
            fragmentManager.beginTransaction().replace(android.R.id.content, prefsFragement).commit();
        }
    }

    private void cancelProgressDialog() {
        if (progressDialogFragment != null && progressDialogFragment.getDialog() != null) {
            progressDialogFragment.getDialog().dismiss();
        }
    }

    private void showProgressDialog(String message) {
        cancelProgressDialog();
        progressDialogFragment = new ProgressDialogFragment();
        progressDialogFragment.setMessage(message);
        progressDialogFragment.show(getFragmentManager(), "downLoading");
    }

}